<template>
  <div class="urgency-indicator">
    <div class="indicator-header">
      <h3 class="title">
        <i class="fas fa-exclamation-triangle"></i>
        紧急程度评估
      </h3>
      <p class="subtitle">基于您的症状信息智能评估</p>
    </div>

    <!-- 紧急程度显示 -->
    <div class="urgency-display">
      <div class="urgency-level" :class="urgencyLevelClass">
        <div class="level-icon">
          <i :class="urgencyIcon"></i>
        </div>
        <div class="level-content">
          <div class="level-title">{{ urgencyTitle }}</div>
          <div class="level-description">{{ urgencyDescription }}</div>
        </div>
        <div class="level-indicator">
          <div class="indicator-bars">
            <div 
              v-for="i in 5" 
              :key="i"
              :class="['indicator-bar', { active: i <= urgencyScore }]"
            ></div>
          </div>
          <div class="indicator-text">{{ urgencyScore }}/5</div>
        </div>
      </div>
    </div>

    <!-- 危险信号检查 -->
    <div class="danger-signals" v-if="dangerSignals.length > 0">
      <h4 class="section-title danger">
        <i class="fas fa-warning"></i>
        检测到危险信号
      </h4>
      <div class="signals-list">
        <div 
          v-for="signal in dangerSignals" 
          :key="signal.id"
          class="signal-item"
        >
          <div class="signal-icon">
            <i :class="signal.icon"></i>
          </div>
          <div class="signal-content">
            <div class="signal-title">{{ signal.title }}</div>
            <div class="signal-description">{{ signal.description }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 就医建议 -->
    <div class="medical-advice">
      <h4 class="section-title">
        <i class="fas fa-user-md"></i>
        就医建议
      </h4>
      <div class="advice-content" :class="urgencyLevelClass">
        <div class="advice-main">
          <div class="advice-action">
            <i :class="adviceIcon"></i>
            <span class="action-text">{{ adviceAction }}</span>
          </div>
          <div class="advice-timeframe">{{ adviceTimeframe }}</div>
        </div>
        <div class="advice-details">
          <ul class="advice-list">
            <li v-for="item in adviceItems" :key="item">{{ item }}</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 科室推荐 -->
    <div class="department-recommendation" v-if="recommendedDepartments.length > 0">
      <h4 class="section-title">
        <i class="fas fa-hospital"></i>
        推荐科室
      </h4>
      <div class="departments-grid">
        <div 
          v-for="dept in recommendedDepartments" 
          :key="dept.id"
          class="department-card"
          @click="selectDepartment(dept)"
        >
          <div class="dept-icon">
            <i :class="dept.icon"></i>
          </div>
          <div class="dept-info">
            <div class="dept-name">{{ dept.name }}</div>
            <div class="dept-reason">{{ dept.reason }}</div>
          </div>
          <div class="dept-priority" :class="dept.priority">
            {{ getDepartmentPriorityText(dept.priority) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 紧急联系方式 -->
    <div class="emergency-contacts" v-if="urgencyLevel === 'critical'">
      <h4 class="section-title critical">
        <i class="fas fa-phone"></i>
        紧急联系方式
      </h4>
      <div class="contacts-grid">
        <div class="contact-item emergency">
          <div class="contact-icon">
            <i class="fas fa-ambulance"></i>
          </div>
          <div class="contact-info">
            <div class="contact-title">急救电话</div>
            <div class="contact-number">120</div>
          </div>
          <el-button type="danger" @click="callEmergency('120')">
            <i class="fas fa-phone"></i>
            拨打
          </el-button>
        </div>
        
        <div class="contact-item">
          <div class="contact-icon">
            <i class="fas fa-hospital"></i>
          </div>
          <div class="contact-info">
            <div class="contact-title">医院急诊</div>
            <div class="contact-number">就近医院</div>
          </div>
          <el-button type="primary" @click="findNearbyHospital">
            <i class="fas fa-map-marker-alt"></i>
            查找
          </el-button>
        </div>
      </div>
    </div>

    <!-- 自我护理建议 -->
    <div class="self-care-advice" v-if="selfCareAdvice.length > 0">
      <h4 class="section-title">
        <i class="fas fa-heart"></i>
        自我护理建议
      </h4>
      <div class="care-advice-list">
        <div 
          v-for="advice in selfCareAdvice" 
          :key="advice.id"
          class="care-advice-item"
        >
          <div class="advice-icon">
            <i :class="advice.icon"></i>
          </div>
          <div class="advice-text">
            <div class="advice-title">{{ advice.title }}</div>
            <div class="advice-detail">{{ advice.detail }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 复查提醒 -->
    <div class="follow-up-reminder">
      <h4 class="section-title">
        <i class="fas fa-calendar-check"></i>
        复查提醒
      </h4>
      <div class="reminder-content">
        <div class="reminder-text">
          <p>{{ followUpMessage }}</p>
        </div>
        <div class="reminder-actions">
          <el-button type="primary" @click="setReminder">
            <i class="fas fa-bell"></i>
            设置提醒
          </el-button>
          <el-button @click="bookAppointment">
            <i class="fas fa-calendar-plus"></i>
            预约挂号
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElButton } from 'element-plus'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  assessmentData: {
    type: Object,
    default: () => ({
      bodyParts: [],
      intensity: {},
      duration: {},
      symptoms: []
    })
  }
})

// Emits
const emit = defineEmits(['department-select', 'emergency-call', 'set-reminder', 'book-appointment'])

// 响应式数据
const urgencyLevel = ref('low')
const urgencyScore = ref(1)
const dangerSignals = ref([])
const recommendedDepartments = ref([])
const selfCareAdvice = ref([])

// 危险信号定义
const dangerSignalDefinitions = [
  {
    id: 'severe_pain',
    condition: (data) => data.intensity?.painLevel >= 8,
    title: '剧烈疼痛',
    description: '疼痛程度达到8分以上，可能需要紧急处理',
    icon: 'fas fa-exclamation-circle'
  },
  {
    id: 'chest_pain',
    condition: (data) => data.bodyParts?.some(part => part.id === 'chest') && data.intensity?.painLevel >= 5,
    title: '胸痛',
    description: '胸部疼痛可能提示心脏或肺部问题',
    icon: 'fas fa-heart'
  },
  {
    id: 'breathing_difficulty',
    condition: (data) => data.symptoms?.includes('dyspnea'),
    title: '呼吸困难',
    description: '呼吸困难可能提示严重的呼吸系统问题',
    icon: 'fas fa-lungs'
  },
  {
    id: 'high_fever',
    condition: (data) => data.symptoms?.includes('fever') && data.intensity?.painLevel >= 7,
    title: '高热',
    description: '高热可能提示严重感染',
    icon: 'fas fa-thermometer-full'
  },
  {
    id: 'head_trauma',
    condition: (data) => data.bodyParts?.some(part => part.id === 'head') && data.duration?.totalMinutes < 60,
    title: '急性头部症状',
    description: '急性头部症状需要排除颅内病变',
    icon: 'fas fa-brain'
  }
]

// 科室定义
const departmentDefinitions = [
  {
    id: 'emergency',
    name: '急诊科',
    icon: 'fas fa-ambulance',
    conditions: ['critical'],
    reason: '需要紧急处理'
  },
  {
    id: 'cardiology',
    name: '心内科',
    icon: 'fas fa-heartbeat',
    conditions: ['chest_pain', 'palpitation'],
    reason: '心脏相关症状'
  },
  {
    id: 'neurology',
    name: '神经内科',
    icon: 'fas fa-brain',
    conditions: ['head', 'dizziness'],
    reason: '神经系统症状'
  },
  {
    id: 'respiratory',
    name: '呼吸内科',
    icon: 'fas fa-lungs',
    conditions: ['cough', 'dyspnea'],
    reason: '呼吸系统症状'
  },
  {
    id: 'gastroenterology',
    name: '消化内科',
    icon: 'fas fa-stomach',
    conditions: ['abdomen', 'nausea'],
    reason: '消化系统症状'
  },
  {
    id: 'orthopedics',
    name: '骨科',
    icon: 'fas fa-bone',
    conditions: ['joints', 'left_arm', 'right_arm', 'left_leg', 'right_leg'],
    reason: '骨骼肌肉症状'
  }
]

// 计算属性
const urgencyLevelClass = computed(() => {
  return `urgency-${urgencyLevel.value}`
})

const urgencyIcon = computed(() => {
  const icons = {
    low: 'fas fa-check-circle',
    moderate: 'fas fa-exclamation-circle',
    high: 'fas fa-exclamation-triangle',
    critical: 'fas fa-skull-crossbones'
  }
  return icons[urgencyLevel.value] || 'fas fa-question-circle'
})

const urgencyTitle = computed(() => {
  const titles = {
    low: '低风险',
    moderate: '中等风险',
    high: '高风险',
    critical: '紧急情况'
  }
  return titles[urgencyLevel.value] || '未知'
})

const urgencyDescription = computed(() => {
  const descriptions = {
    low: '症状相对轻微，可以观察或择期就医',
    moderate: '症状需要关注，建议及时就医',
    high: '症状较为严重，建议尽快就医',
    critical: '可能存在生命危险，需要立即就医'
  }
  return descriptions[urgencyLevel.value] || '无法评估'
})

const adviceIcon = computed(() => {
  const icons = {
    low: 'fas fa-home',
    moderate: 'fas fa-hospital',
    high: 'fas fa-ambulance',
    critical: 'fas fa-exclamation-triangle'
  }
  return icons[urgencyLevel.value] || 'fas fa-question'
})

const adviceAction = computed(() => {
  const actions = {
    low: '居家观察',
    moderate: '择期就医',
    high: '尽快就医',
    critical: '立即就医'
  }
  return actions[urgencyLevel.value] || '咨询医生'
})

const adviceTimeframe = computed(() => {
  const timeframes = {
    low: '可在1-2天内观察症状变化',
    moderate: '建议在24小时内就医',
    high: '建议在6小时内就医',
    critical: '立即前往急诊科'
  }
  return timeframes[urgencyLevel.value] || '请咨询医生'
})

const adviceItems = computed(() => {
  const items = {
    low: [
      '注意休息，保持充足睡眠',
      '多喝水，保持身体水分',
      '观察症状变化，如有加重及时就医',
      '避免剧烈运动'
    ],
    moderate: [
      '准备相关检查资料',
      '记录症状变化情况',
      '避免自行用药',
      '如症状加重立即就医'
    ],
    high: [
      '立即停止当前活动',
      '准备就医所需物品',
      '联系家人陪同就医',
      '如症状恶化立即拨打120'
    ],
    critical: [
      '立即拨打120急救电话',
      '保持冷静，等待救援',
      '如有意识丧失，立即进行急救',
      '通知家属'
    ]
  }
  return items[urgencyLevel.value] || []
})

const followUpMessage = computed(() => {
  const messages = {
    low: '建议1周后复查，如症状持续或加重请及时就医',
    moderate: '建议3-5天后复查，密切观察症状变化',
    high: '建议1-2天后复查，必要时随时就医',
    critical: '需要密切医学观察，按医嘱定期复查'
  }
  return messages[urgencyLevel.value] || '请按医嘱复查'
})

// 方法
const assessUrgency = (data) => {
  let score = 1
  let level = 'low'
  const signals = []
  
  // 检查危险信号
  dangerSignalDefinitions.forEach(signal => {
    if (signal.condition(data)) {
      signals.push(signal)
      score += 1
    }
  })
  
  // 基于疼痛程度评分
  if (data.intensity?.painLevel) {
    if (data.intensity.painLevel >= 8) score += 2
    else if (data.intensity.painLevel >= 6) score += 1
  }
  
  // 基于影响程度评分
  if (data.intensity?.impactLevel) {
    if (data.intensity.impactLevel === 'unable_function') score += 2
    else if (data.intensity.impactLevel === 'severe_impact') score += 1
  }
  
  // 基于持续时间评分
  if (data.duration?.isOngoing && data.duration?.totalMinutes > 1440) {
    score += 1
  }
  
  // 确定紧急程度
  if (score >= 5) level = 'critical'
  else if (score >= 4) level = 'high'
  else if (score >= 3) level = 'moderate'
  else level = 'low'
  
  urgencyScore.value = Math.min(score, 5)
  urgencyLevel.value = level
  dangerSignals.value = signals
  
  // 更新科室推荐
  updateDepartmentRecommendations(data)
  
  // 更新自我护理建议
  updateSelfCareAdvice(level)
}

const updateDepartmentRecommendations = (data) => {
  const departments = []
  
  // 紧急情况推荐急诊科
  if (urgencyLevel.value === 'critical') {
    departments.push({
      ...departmentDefinitions.find(d => d.id === 'emergency'),
      priority: 'critical'
    })
  }
  
  // 基于身体部位推荐科室
  data.bodyParts?.forEach(part => {
    departmentDefinitions.forEach(dept => {
      if (dept.conditions.includes(part.id) && !departments.find(d => d.id === dept.id)) {
        departments.push({
          ...dept,
          priority: urgencyLevel.value === 'high' ? 'high' : 'normal'
        })
      }
    })
  })
  
  // 基于症状类型推荐科室
  data.symptoms?.forEach(symptom => {
    departmentDefinitions.forEach(dept => {
      if (dept.conditions.includes(symptom) && !departments.find(d => d.id === dept.id)) {
        departments.push({
          ...dept,
          priority: urgencyLevel.value === 'high' ? 'high' : 'normal'
        })
      }
    })
  })
  
  recommendedDepartments.value = departments.slice(0, 4)
}

const updateSelfCareAdvice = (level) => {
  const advice = []
  
  if (level === 'low' || level === 'moderate') {
    advice.push(
      {
        id: 'rest',
        title: '充分休息',
        detail: '保证充足的睡眠，避免过度劳累',
        icon: 'fas fa-bed'
      },
      {
        id: 'hydration',
        title: '补充水分',
        detail: '多喝温水，保持身体水分平衡',
        icon: 'fas fa-tint'
      },
      {
        id: 'diet',
        title: '清淡饮食',
        detail: '选择易消化的食物，避免刺激性食品',
        icon: 'fas fa-apple-alt'
      }
    )
  }
  
  if (level === 'low') {
    advice.push({
      id: 'exercise',
      title: '适度活动',
      detail: '进行轻度运动，促进血液循环',
      icon: 'fas fa-walking'
    })
  }
  
  selfCareAdvice.value = advice
}

const getDepartmentPriorityText = (priority) => {
  const texts = {
    critical: '紧急',
    high: '优先',
    normal: '推荐'
  }
  return texts[priority] || '推荐'
}

const selectDepartment = (department) => {
  emit('department-select', department)
}

const callEmergency = (number) => {
  emit('emergency-call', number)
  ElMessage.warning('请直接拨打急救电话：' + number)
}

const findNearbyHospital = () => {
  ElMessage.info('正在查找附近医院...')
  // 这里可以集成地图API
}

const setReminder = () => {
  emit('set-reminder', {
    urgencyLevel: urgencyLevel.value,
    followUpTime: getFollowUpTime()
  })
}

const bookAppointment = () => {
  emit('book-appointment', {
    departments: recommendedDepartments.value,
    urgencyLevel: urgencyLevel.value
  })
}

const getFollowUpTime = () => {
  const now = new Date()
  const followUpTimes = {
    low: 7 * 24 * 60 * 60 * 1000, // 7天
    moderate: 3 * 24 * 60 * 60 * 1000, // 3天
    high: 1 * 24 * 60 * 60 * 1000, // 1天
    critical: 0 // 立即
  }
  return new Date(now.getTime() + (followUpTimes[urgencyLevel.value] || 0))
}

// 监听评估数据变化
watch(() => props.assessmentData, (newData) => {
  if (newData) {
    assessUrgency(newData)
  }
}, { deep: true, immediate: true })
</script>

<style scoped>
.urgency-indicator {
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.indicator-header {
  text-align: center;
  margin-bottom: 25px;
}

.title {
  color: #2c5aa0;
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.subtitle {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.section-title {
  color: #2c5aa0;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 15px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title.danger {
  color: #f5222d;
}

.section-title.critical {
  color: #a8071a;
}

.urgency-display {
  margin-bottom: 25px;
}

.urgency-level {
  padding: 20px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 20px;
  transition: all 0.3s ease;
}

.urgency-low {
  background: linear-gradient(135deg, #52c41a, #73d13d);
  color: white;
}

.urgency-moderate {
  background: linear-gradient(135deg, #faad14, #ffc53d);
  color: white;
}

.urgency-high {
  background: linear-gradient(135deg, #fa541c, #ff7a45);
  color: white;
}

.urgency-critical {
  background: linear-gradient(135deg, #f5222d, #ff4d4f);
  color: white;
  animation: pulse 2s infinite;
}

.level-icon {
  font-size: 32px;
  min-width: 50px;
}

.level-content {
  flex: 1;
}

.level-title {
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 5px;
}

.level-description {
  font-size: 14px;
  opacity: 0.9;
}

.level-indicator {
  text-align: center;
}

.indicator-bars {
  display: flex;
  gap: 3px;
  margin-bottom: 5px;
}

.indicator-bar {
  width: 8px;
  height: 20px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  transition: all 0.3s ease;
}

.indicator-bar.active {
  background: rgba(255, 255, 255, 0.9);
}

.indicator-text {
  font-size: 12px;
  font-weight: 600;
}

.danger-signals {
  margin-bottom: 25px;
  padding: 20px;
  background: #fff2f0;
  border-radius: 8px;
  border-left: 4px solid #f5222d;
}

.signals-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.signal-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #ffccc7;
}

.signal-icon {
  color: #f5222d;
  font-size: 18px;
  min-width: 24px;
}

.signal-title {
  font-weight: 600;
  color: #f5222d;
  margin-bottom: 4px;
}

.signal-description {
  font-size: 14px;
  color: #666;
}

.medical-advice {
  margin-bottom: 25px;
  padding: 20px;
  border-radius: 8px;
}

.medical-advice.urgency-low {
  background: #f6ffed;
  border-left: 4px solid #52c41a;
}

.medical-advice.urgency-moderate {
  background: #fffbe6;
  border-left: 4px solid #faad14;
}

.medical-advice.urgency-high {
  background: #fff2e8;
  border-left: 4px solid #fa541c;
}

.medical-advice.urgency-critical {
  background: #fff2f0;
  border-left: 4px solid #f5222d;
}

.advice-main {
  margin-bottom: 15px;
}

.advice-action {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}

.advice-timeframe {
  font-size: 14px;
  color: #666;
}

.advice-list {
  margin: 0;
  padding-left: 20px;
}

.advice-list li {
  margin-bottom: 6px;
  font-size: 14px;
}

.department-recommendation {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #1890ff;
}

.departments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.department-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  cursor: pointer;
  transition: all 0.3s ease;
}

.department-card:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.dept-icon {
  font-size: 20px;
  color: #1890ff;
  min-width: 24px;
}

.dept-info {
  flex: 1;
}

.dept-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.dept-reason {
  font-size: 12px;
  color: #666;
}

.dept-priority {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.dept-priority.critical {
  background: #f5222d;
  color: white;
}

.dept-priority.high {
  background: #fa541c;
  color: white;
}

.dept-priority.normal {
  background: #1890ff;
  color: white;
}

.emergency-contacts {
  margin-bottom: 25px;
  padding: 20px;
  background: #fff2f0;
  border-radius: 8px;
  border-left: 4px solid #f5222d;
}

.contacts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  border: 2px solid #ffccc7;
}

.contact-item.emergency {
  border-color: #f5222d;
  background: #fff2f0;
}

.contact-icon {
  font-size: 24px;
  color: #f5222d;
  min-width: 30px;
}

.contact-info {
  flex: 1;
}

.contact-title {
  font-weight: 600;
  margin-bottom: 4px;
}

.contact-number {
  font-size: 18px;
  font-weight: 700;
  color: #f5222d;
}

.self-care-advice {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #52c41a;
}

.care-advice-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.care-advice-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #d9f7be;
}

.advice-icon {
  color: #52c41a;
  font-size: 16px;
  min-width: 20px;
  margin-top: 2px;
}

.advice-title {
  font-weight: 600;
  margin-bottom: 4px;
}

.advice-detail {
  font-size: 14px;
  color: #666;
}

.follow-up-reminder {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #722ed1;
}

.reminder-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.reminder-text {
  flex: 1;
}

.reminder-actions {
  display: flex;
  gap: 10px;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.8; }
  100% { opacity: 1; }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .urgency-indicator {
    padding: 15px;
  }
  
  .urgency-level {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }
  
  .departments-grid,
  .contacts-grid {
    grid-template-columns: 1fr;
  }
  
  .reminder-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .reminder-actions {
    justify-content: center;
  }
}
</style>